<script setup lang="ts">
const { type, id } = defineProps<{ type: string; id: number }>()
const { add, findAll, collection } = useComment()
const { isLogin } = useAuth()
const route = useRoute()
const form = reactive({ content: '', type, id })
await findAll(type, id)
const onSubmit = async () => {
  const comment = await add(form)
  form.content = ''
  collection.value?.push(comment)
}
onMounted(() => {
  const el = document.querySelector('#comment-' + route.query.commentId)

  if (el) {
    el.scrollIntoView({ block: 'start', behavior: 'smooth' })
  }
})
</script>

<template>
  <main class="">
    <HdCard>
      <template #header>评论</template>
      <CommentItem
        v-for="comment of collection"
        :comment="comment"
        :id="comment.id"
        :type="type"
        :key="comment.id"
        :collection="collection">
        <CommentItem
          v-for="reply of comment.replys"
          :comment="reply"
          :id="comment.id"
          :type="type"
          :key="comment.id"
          class="ml-8 bg-gray-50"
          :collection="collection" />
      </CommentItem>
      <div v-if="isLogin()" class="mt-5">
        <HdMarkdownEditor v-model="form.content" />
        <HdError name="content" />
        <el-button type="primary" size="default" @click="onSubmit" class="mt-2">发表</el-button>
      </div>
      <div v-else class="flex justify-center">
        <el-button type="primary" size="default" @click="$router.push({ name: 'login' })">登录后发表</el-button>
      </div>
    </HdCard>
  </main>
</template>
<style lang="scss" scoped></style>
